/**
 * 
 */
package com.youxin.cpcenter.pt.service;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.jdbc.core.JdbcTemplate;

import com.youxin.busfoundation.common.es.SearchComapny;
import com.youxin.busfoundation.common.es.bean.CompanyInfoBean;
import com.youxin.busfoundation.common.es.bean.RequestQueryLeadsBean;
import com.youxin.busfoundation.utils.es.EsBasePage;
import com.youxin.cpcenter.pt.common.PtConfig;
import com.youxin.cpcenter.pt.common.RedisKeyForPt;
import com.youxin.cpcenter.pt.service.process.Identify;
import com.youxin.foundation.db.redis.RedisClusterCommand;
import com.youxin.foundation.utils.ArrayUtils;
import com.youxin.foundation.utils.JsonUtils;
import com.youxin.foundation.utils.StringUtils;
import com.youxin.foundation.utils.collections.CollectionsUtils;
import com.youxin.foundation.utils.thread.BaseThreadPool;
import com.youxin.foundation.utils.thread.ScheduleThreadPool;

import redis.clients.jedis.JedisCluster;

/**
 * @author yingde.cao
 * @date 2017年12月20日
 * @version 1.0
 */
public class PtTask {
	private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(PtTask.class);
	private AtomicInteger count = new AtomicInteger();
	private static PtTask task = new PtTask();
	private JdbcTemplate jdbcTemplate;
	private Map<String, String> tokens=new ConcurrentHashMap<>();
	public static PtTask instanse() {
		return task;
	}
	
	public Map<String, String> getTokens() {
		return tokens;
	}

	public void setCompanyToken(String uid,String token){
		tokens.put(uid, token);
	}
	
	public Map<String, String> getTokenMap(CompanyInfoBean companyInfoBean){
		 Map<String, String> map=new HashMap<>();
		 String token=tokens.get(companyInfoBean.getUid());
		 map.put("token", token);
		 return map;
	}
	
	public String getCompanyToken(String uid)
	{
		return tokens.get(uid);
	}

	public void run(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
		// CallService.subscribe();

		loadCompanyData();

//		SingleThreadPool.addTask(new Runnable() {
//			@Override
//			public void run() {
//				loadCompanyData();
//			}
//		});

		ScheduleThreadPool.scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				dealCompanyInfo();
			}
		}, 2000, 10000);

	}

	private void clearData(String companyUid) {
		String deleteWhere = "where company_uid='" + companyUid + "'";
		String sql = "delete from tb_ent_tryout_info " + deleteWhere;
		jdbcTemplate.execute(sql);

		sql = "delete from tb_ent_member_identify_capital " + deleteWhere;
		jdbcTemplate.execute(sql);

		sql = "delete from tb_ent_member_info " + deleteWhere;
		jdbcTemplate.execute(sql);

		sql = "delete from tb_ent_member_identify " + deleteWhere;
		jdbcTemplate.execute(sql);

		sql = "delete from tb_ent_member_identify_capital_his " + deleteWhere;
		jdbcTemplate.execute(sql);

		sql = "delete from tb_ent_member_identify_capital_list " + deleteWhere;
		jdbcTemplate.execute(sql);

	}

	/**
	 * 加载公司信息
	 * 
	 * @description
	 */
	private void loadCompanyData() {
		try {
			final String lockGroupKey = RedisKeyForPt.COMPANY_IMPORT_FLAG + ":lock";
			RedisClusterCommand.instance().lockCommand(lockGroupKey, 60000, (redisCluster) -> {
				try {
					try {
						JedisCluster redis = RedisClusterCommand.instance().getRedisCluster();
						redis.del(RedisKeyForPt.COMPANY_SOURCE_LIST);
						redis.del(RedisKeyForPt.COMPANY_RETAIN_LIST);
						redis.del(RedisKeyForPt.COMPANY_INFO_LOAD_PAGE_INDEX);
						List<String> urlList=PtConfig.URL_SUFFIXS;
						for (String url : urlList) {
							redis.del("url:"+url);
						}
						Long length = redis.llen(RedisKeyForPt.COMPANY_SOURCE_LIST);
						while (true) {
							Long pageIndex = RedisClusterCommand.instance().getRedisCluster()
									.incr(RedisKeyForPt.COMPANY_INFO_LOAD_PAGE_INDEX);
							SearchComapny<CompanyInfoBean> searchComapny = new SearchComapny<>();
							RequestQueryLeadsBean queryLeadsBean = new RequestQueryLeadsBean();
							queryLeadsBean.setPageNo(pageIndex.intValue());
							queryLeadsBean.setPageSize(100);
							EsBasePage<Object> result = searchComapny.queryList(queryLeadsBean, CompanyInfoBean.class);
							if(ArrayUtils.isEmpty(result.getResults()))
							{
								break;
							}
							List<CompanyInfoBean> list = CollectionsUtils.listClassConvert(result.getResults());
							for (CompanyInfoBean item : list) {
								clearData(item.getUid());
								String json = JsonUtils.objectToFasterxmlJsonString(item);
								redis.rpush(RedisKeyForPt.COMPANY_SOURCE_LIST, json);
								redis.rpush(RedisKeyForPt.COMPANY_RETAIN_LIST, json);
							}
							length = redis.llen(RedisKeyForPt.COMPANY_SOURCE_LIST);
						}

					} catch (Exception e) {
						logger.error(e);
					}
				} catch (Exception e) {
					logger.error("执行任务时异常:" + lockGroupKey, e);
				}
			});

		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 处理公司信息
	 * 
	 * @description
	 */
	public void dealCompanyInfo() {
		try {
			JedisCluster redis = RedisClusterCommand.instance().getRedisCluster();
			for (int i = 0; i < 10; ++i) {
				String json = redis.lpop(RedisKeyForPt.COMPANY_SOURCE_LIST);
				if (StringUtils.isNullOrEmpty(json))
					return;
				CompanyInfoBean bean = JsonUtils.stringToFasterxmlObject(json, CompanyInfoBean.class);
				int sourceCount = count.get();
				if (!count.compareAndSet(sourceCount, sourceCount + 1)) {
					//continue;
				}

				//process(bean);

				BaseThreadPool.addTask(new Runnable() {
					@Override
					public void run() {
						process(bean);
					}
				});
			}

		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 处理流程
	 * 
	 * @description
	 * @param bean
	 */
	private void process(CompanyInfoBean bean) {
		Identify.identifyAndLogin(bean);
	}

}
